﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using System.IO;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;

namespace wfaResClient
{
    public class DeviceControl
    {
        UploadClass upload = new UploadClass();
        public Int16 EquipmentChannel;//通道ID
        public void openDevice(Int32 Handles)
        {
            try
            {
                agin:
                //判断设备是否存在，存在打开设备
                if (BriSDKLib.QNV_OpenDevice(BriSDKLib.ODT_LBRIDGE, 0, "") <= 0 || BriSDKLib.QNV_DevInfo(0, BriSDKLib.QNV_DEVINFO_GETCHANNELS) <= 0)//判断设备是否存在
                {
                    if (mes("设备不存在，请检查设备线路\r是否再次检测", "信息提示"))
                    {
                        goto agin;
                    }
                }
                else
                {
                    for (Int16 i = 0; i < BriSDKLib.QNV_DevInfo(-1, BriSDKLib.QNV_DEVINFO_GETCHANNELS); i++)//否则执行打开设备
                    {
                        BriSDKLib.QNV_Event(i, BriSDKLib.QNV_EVENT_REGWND, Handles, "", new StringBuilder(0), 0);
                        BriSDKLib.QNV_SetDevCtrl(i, BriSDKLib.QNV_CTRL_PLAYMUX, 1);//默认打开设备就打开到线路声音
                        if (BriSDKLib.QNV_SetParam(i, BriSDKLib.QNV_PARAM_CITYCODE, 23) < 0)//设置本地区号
                        {
                            mes("设置本地区号失败");
                        }
                        EquipmentChannel = i;
                    }
                }
            }
            catch(Exception ex)
            {
                mes("启动设备异常" + ex.ToString());
            }

        }
        public void ShutDownEquipment()
        {
            if (BriSDKLib.QNV_CloseDevice(BriSDKLib.ODT_ALL, 0) < 0)
                mes("关闭设备失败");
        }
        public void RebootDevice(Int32 Handles)
        {
            ShutDownEquipment();
            openDevice(Handles);
        }
        public void OffHorn()
        {
            if (BriSDKLib.QNV_SetDevCtrl(EquipmentChannel, BriSDKLib.QNV_CTRL_DOPLAY, 0) < 0)
                mes("喇叭关闭失败");
        }
        public void Dialing(string PhNumber)
        {
            try
            {
                switch (BriSDKLib.QNV_GetDevCtrl(EquipmentChannel, BriSDKLib.QNV_CTRL_DOPLAY))//检测喇叭是否打开0关1开
                {
                    case 0:
                        BriSDKLib.QNV_SetDevCtrl(EquipmentChannel, BriSDKLib.QNV_CTRL_DOPLAY, 1);//打开喇叭
                        BriSDKLib.QNV_General(EquipmentChannel, BriSDKLib.QNV_GENERAL_STARTDIAL, 0, PhNumber);//拨打电话
                        if (Properties.Settings.Default.AutomaticRecording == 1)//自动录音判断
                        {
                            //CallRecording(publicData.IPone);
                            ////threadCallRecording();//开始录音
                        }
                        break;
                    case 1:
                        BriSDKLib.QNV_General(EquipmentChannel, BriSDKLib.QNV_GENERAL_STARTDIAL, 0, PhNumber);//拨打电话
                        if (Properties.Settings.Default.AutomaticRecording == 1)//自动录音判断
                        {
                            //CallRecording(publicData.IPone);
                            ////threadCallRecording();//开始录音
                        }
                        break;
                    default:
                        mes("检测喇叭异常，是否打开设备");
                        break;
                }
            }
            catch(Exception ex)
            {
                mes("拨打电话：" + ex.ToString());
            }
        }
        public void StopDialing()
        {
            try
            {
                switch (BriSDKLib.QNV_General(EquipmentChannel, BriSDKLib.QNV_GENERAL_ISDIALING, 0, ""))//执行获得反馈值
                {
                    case 1:
                        if (BriSDKLib.QNV_General(EquipmentChannel, BriSDKLib.QNV_GENERAL_STOPDIAL, 0, "") > 0)
                        {
                            mes("停止拨号成功");
                        }
                        break;
                    case 0:
                        mes("当前设备没有在拨号");
                        break;
                    default:
                        mes("停止拨号-设备异常");
                        break;
                }
            }
            catch(Exception ex)
            {
                mes("停止拨号：" + ex.ToString());
            }
        }
        public void AnswerPhone()
        {
            try
            {
                switch (BriSDKLib.QNV_GetDevCtrl(EquipmentChannel, BriSDKLib.QNV_CTRL_DOPLAY))//检测喇叭是否打开0关1开
                {
                    case 0:
                        BriSDKLib.QNV_SetDevCtrl(EquipmentChannel, BriSDKLib.QNV_CTRL_DOPLAY, 1);//打开喇叭
                        BriSDKLib.QNV_SetDevCtrl(EquipmentChannel, BriSDKLib.QNV_CTRL_DOHOOK, 1);//接听电话
                        break;
                    case 1:
                        BriSDKLib.QNV_SetDevCtrl(EquipmentChannel, BriSDKLib.QNV_CTRL_DOHOOK, 1);
                        break;
                    default:
                        mes("接听电话-设备异常");
                        break;
                }
            }
            catch(Exception ex)
            {
                mes("接听电话：" + ex.ToString());
            }
        }
        /// <summary>
        /// 挂断电话
        /// </summary>
        public void HangUp()
        {
            try
            {
                switch (BriSDKLib.QNV_GetDevCtrl(EquipmentChannel, BriSDKLib.QNV_CTRL_DOPLAY))//检测喇叭是否打开0关1开
                {
                    case 0:
                        BriSDKLib.QNV_General(EquipmentChannel, BriSDKLib.QNV_GENERAL_STARTFLASH, BriSDKLib.FT_ALL, "");
                        StopRecording();//录音完成
                        PluggedSpring();
                        break;
                    case 1:
                        BriSDKLib.QNV_SetDevCtrl(EquipmentChannel, BriSDKLib.QNV_CTRL_DOPLAY, 0);//关闭喇叭
                        BriSDKLib.QNV_General(EquipmentChannel, BriSDKLib.QNV_GENERAL_STARTFLASH, BriSDKLib.FT_ALL, "");//挂断电话
                        StopRecording();//录音完成
                        PluggedSpring();
                        break;
                    default:
                        mes("检测喇叭异常，是否打开设备");
                        break;
                }
            }
            catch(Exception ex)
            {
                mes("挂断电话：" + ex.ToString());
            }
        }
        /// <summary>
        /// 拍插簧
        /// </summary>
        public void PluggedSpring()
        {
            switch(BriSDKLib.QNV_General(EquipmentChannel, BriSDKLib.QNV_GENERAL_ISFLASHING, 0, ""))
            {
                case 0:
                    BriSDKLib.QNV_General(EquipmentChannel, BriSDKLib.QNV_GENERAL_STARTFLASH, BriSDKLib.FT_ALL, "");
                    break;
                case 1:
                    break;
                default:
                    MessageBox.Show("拍插簧-异常");
                    break;
            }
           
        }
        public struct tag_pstn_Data
        {
            //public Int32 lPlayFileHandle;//播放句柄
            public Int32 lRecFileHandle;//录音句柄            
        }
        tag_pstn_Data[] m_tagpstnData = new tag_pstn_Data[BriSDKLib.MAX_CHANNEL_COUNT];
        /// <summary>
        /// 电话录音
        /// </summary>
        /// <param name="RName">当前用户下拨打的电话</param>
        /// <returns></returns>
        public void CallRecording(string RName)
        {
            try
            {
                string PathUrl;//默认保存路径
                if (Properties.Settings.Default.RecordingUrl == "" || Properties.Settings.Default.RecordingUrl == null)
                {
                    PathUrl = Application.StartupPath + "\\RecFile\\";
                }
                else
                {
                    PathUrl = Properties.Settings.Default.RecordingUrl + "\\";
                }
                string RecordingName;//默认保存文件名为日期被呼叫号码的后五位
                RecordingName = RName.Remove(0,5) +string.Format("{0:yyyy/MM/dd/HH/mm/ss}", DateTime.Now) + ".wav";
                if (PathUrl != ""&&PathUrl!=null)
                {
                    RecordingVolume(Convert.ToInt32(Properties.Settings.Default.RecordingValue)*100);//设置录音音量
                    string AddRName_Url = PathUrl + RecordingName;
                    m_tagpstnData[EquipmentChannel].lRecFileHandle = BriSDKLib.QNV_RecordFile(EquipmentChannel, BriSDKLib.QNV_RECORD_FILE_START, 0, BriSDKLib.RECORD_MASK_ECHO, AddRName_Url);//默认回音抵消压缩 3 32/kbs压缩率
                    PublicData.FileUrl = AddRName_Url;//更新文件路径和文件名
                    if (m_tagpstnData[0].lRecFileHandle <= 0)
                    {
                        mes("录音失败");
                    }
                }
                else
                {
                    m_tagpstnData[EquipmentChannel].lRecFileHandle = BriSDKLib.QNV_RecordFile(EquipmentChannel, BriSDKLib.QNV_RECORD_FILE_START, 3, BriSDKLib.RECORD_MASK_ECHO, RecordingName);//保存到默认位置
                    if (m_tagpstnData[0].lRecFileHandle <= 0)
                    {
                        mes("录音失败");
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }
        }
        /// <summary>
        /// 设置录音音量
        /// </summary>
        /// <param name="Volume">值</param>
        public void RecordingVolume(int Volume)
        {
            if (BriSDKLib.QNV_SetParam(EquipmentChannel, BriSDKLib.QNV_PARAM_AM_LINEIN, Volume) < 0)
            {
                mes("设置录音音量失败");
            }
        }
        /// <summary>
        /// 停止录音，录音完成
        /// </summary>
        /// <returns></returns>
        public void StopRecording()
        {
            if (PublicData.IsRecding)
            {
                try
                {
                    if (m_tagpstnData[EquipmentChannel].lRecFileHandle > 0)
                    {
                        long lRet = BriSDKLib.QNV_RecordFile(EquipmentChannel, BriSDKLib.QNV_RECORD_FILE_STOP, m_tagpstnData[EquipmentChannel].lRecFileHandle, 0, "");
                        m_tagpstnData[EquipmentChannel].lRecFileHandle = 0;
                        upload.upFile(PublicData.LoginID, PublicData.Aid, PublicData.Name, PublicData.IPone, PublicData.CallType, PublicData.CallState, PublicData.CreaTime, PublicData.Updatetime, PublicData.FileUrl,PublicData.UploadUrl);
                    }
                    else
                        mes("你可能未打开录音");
                }
                catch (Exception ex)
                {
                    mes("停止录音：" + ex.ToString());
                }
            }
            else
            {
                upload.upFile(PublicData.LoginID, PublicData.Aid, PublicData.Name, PublicData.IPone, PublicData.CallType, PublicData.CallState, PublicData.CreaTime, PublicData.Updatetime, PublicData.CallRecordUpload);
            }
        }
        /// <summary>
        /// 打开看门狗，pc一段时间不与设备通信，自动复位
        /// </summary>
        public void DoorDog()
        {
            if (BriSDKLib.QNV_SetDevCtrl(0, BriSDKLib.QNV_CTRL_WATCHDOG, 1) > 0)
            {
                return;
            }
            else
            {
                mes("看门狗打开失败");
            }
        }
        public void mes(string content)
        {
            MessageBox.Show(content, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        public bool mes(string content, string title)
        {
            DialogResult result = MessageBox.Show(content, title, MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
            if (result == DialogResult.Retry)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}